package com.zhugang.week11;

/**
 * @program algorithms
 * @description: longestCommonSubsequence2
 * @author: chanzhugang
 * @create: 2022/09/06 07:40
 */
public class LongestCommonSubsequence2 {

    /**
     * 1143 最长公共子序列
     *
     * @param text1
     * @param text2
     * @return
     */
    public int longestCommonSubsequence2(String text1, String text2) {
        int n = text1.length();
        int m = text2.length();
        char[] t1 = text1.toCharArray();
        char[] t2 = text2.toCharArray();

        // 长度为i的子串和长度为j的子串的LCS
        int[][] dp = new int[n + 1][m + 1];
        // 初始化第一行、第一列
        for (int i = 0; i <= n; i++) {
            dp[i][0] = 0;
        }
        for (int j = 0; j <= m; j++) {
            dp[0][j] = 0;
        }

        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (t1[i - 1] == t2[j - 1]) {
                    // 从左、上、左上（相匹配+1）转换来
                    dp[i][j] = max3(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1] + 1);
                } else {
                    dp[i][j] = max3(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
                }
            }
        }
        return dp[n][m];
    }

    private int max3(int a, int b, int c) {
        return Math.max(Math.max(a, b), c);
    }
}